import express from 'express';
import CryptoJS from 'crypto-js';
import crypto from 'crypto';
import { Base64 } from 'js-base64'
import CONFIG from '../../../config/config.config'
import ttApi from '../../lib/ttapi'; // 头条接口API
import { User } from '../../modal/index'; // 数据库实体类
import { statusList, sequelizeStatus } from '../../common/status'; // 状态码对照
import { checkPermission, aesEncrypt } from '../../utils/utils'; // 工具类

const router = express.Router();
const minLevel = 0; // 允许调用接口的最低等级

router.post('/', async function (Request, Response, next) {
  let param = Request.body
  let openId = ''
  await getSessionKey(param.code, param.anonymousCode, Response).then(res => {
    openId = res.openid
  });

  let userParam = {
    ...param.userInfo,
    openId: openId,
  }
  console.log(userParam)

  User.Modal.upsert(userParam).then(async res => {
    await getUserIdByOpenId(openId).then(res => {
      // 构造token并存储
      let tokenOrigin = `{"uid":"${res.id}","timeStamp":"${new Date().valueOf()}"}`
      Response.append('token', aesEncrypt(tokenOrigin));
      // Response.cookie("token", tokenOrigin, { maxAge: 1000 * 60 * 60 * 24, httpOnly: true, signed: true });
    });
    // res为true则新增，false则更新
    let msg = '登陆成功'
    if (res === true) {
      msg = '一键注册成功'
    }
    Response.json({
      data: msg
    })
  }).catch(err => {
    console.log(err)
    Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
  });
});

function getSessionKey(code, anonymousCode, Response) {
  // 通过code获取sessionKey
  return new Promise((resolve, reject) => {
    ttApi.codeToSession({ code: code, anonymous_code: anonymousCode }).then(res => {
      if (res.errcode && res.errmsg) {
        Response.status(300).send({ message: res.errmsg });
      } else {
        resolve(res) // openid
      }
    })
  })
}

function getUserIdByOpenId(openId, Response) {
  // 通过openId获取用户id
  return new Promise((resolve, reject) => {
    User.Modal.findAll({
      where: {
        openId: openId,
      },
      raw: true,
    }).then(res => {
      if (res && res.length > 0) {
        resolve(res[0])
      } else {
        Response.status(300).send({ message: "查询用户失败，请提供正确openId" });
      }
    }).catch(err => {
      console.log(err.name)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  })
}

module.exports = router;